package com.ai.api.intercepter;

import com.ai.utils.RedisOperator;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 登录拦截,未登录成功禁止访问接口
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisOperator redisOperator;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        // 白名单检查:登录或者是加载静态资源
        if (uri.contains("/login")|| uri.contains("/css/")  || uri.contains("/js/")) {
            return true; // 放行白名单
        }
        // 检查redis中的登录标记
        String adminID = redisOperator.get("ADMIN_ID" + ":");
        if (!StringUtils.isBlank(adminID)) {
            return true; // 已登录，放行
        }
        // 未登录，重定向到登录页
        response.sendRedirect(request.getContextPath() + "/login");
        return false; // 拦截请求
    }
}
